package com.iot08.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.iot08.api.utils.buckettool.BaseBucketTool;
import com.iot08.api.utils.request.ParamHandle;
import com.iot08.api.vo.request.ChatGroupGetMessageReqVO;
import com.iot08.api.vo.request.IdsParamReqVO;
import com.iot08.common.entity.app.DevicePhotograph;
import com.iot08.common.entity.app.ResetDevice;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.CollectionUtil;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseMap;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2021/1/22 18:28
 */
@Slf4j
@Service
public class DevicePhotographService extends BaseService<DevicePhotograph> {

    @Resource
    private ResetDeviceService resetDeviceService;
    @Resource
    private BaseBucketTool baseBucketTool;

    /**
     * @param devicePhotograph
     * @time: 2021/1/22 18:32
     * @author: Rock
     * @version 1.0
     */
    @Override
    public DevicePhotograph save(DevicePhotograph devicePhotograph) {
        //所有记录的失效时间天数 3个月
        devicePhotograph.setTime(DateUtil.nowTimestampToDouble());
        devicePhotograph.setExpiryAt(DateUtil.getSystemExpiryAt());
        return mongoTemplate.save(devicePhotograph);
    }

    /**
     * @param imei
     * @param vo
     * @time: 2021/2/4 11:38
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap getPhotoGraph(String imei, ChatGroupGetMessageReqVO vo) {
        long resetTime = 0;
        ResetDevice resetDevice = resetDeviceService.findById(imei);
        if (resetDevice != null && resetDevice.getResetTime() != null) {
            resetTime = resetDevice.getResetTime().getTime() / 1000;
        }
        ResponseMap res = ResponseMap.success();
        List<Map<String, Object>> photoList = new ArrayList<>();
        Document query = new Document();
        query.append("i", imei);
        //参数query处理
        ParamHandle.queryParamHandle(query, vo.getQuery());
        FindIterable<Document> document = this.findDoc(query, Filters.eq("_id", vo.getSort()), vo.getPage(), vo.getNum());
        List<String> ids = new ArrayList<>();
        for (Document doc : document) {
            if (StringUtil.isNumeric(doc.get("t")) && Double.parseDouble(doc.get("t").toString()) > resetTime) {
                ids.add(doc.get("_id").toString());
                Map<String, Object> temp = new HashMap<>();
                temp.put("id", doc.get("_id").toString());
                temp.put("url", baseBucketTool.getDOMAIN() + BaseBucketTool.PHOTOGRAPH_COMMON_PATH + doc.get("image"));
                temp.put("thumbURL", baseBucketTool.getDOMAIN() + BaseBucketTool.PHOTOGRAPH_COMMON_PATH + doc.get("thumb"));
                temp.put("time", StringUtil.isNumeric(doc.get("t")) ? new Double(doc.get("t").toString()) : 0);
                photoList.add(temp);
            }
        }
        //排序处理
        CollectionUtil.sortDouble(photoList, "time", 2);
        res.put("photos", photoList);
        return res;
    }

    /**
     * 删除远程照片
     *
     * @param imei
     * @param vo
     * @time: 2021/2/4 12:10
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap delPhotoGraph(String imei, IdsParamReqVO vo) {
        JSONArray idArr = JSON.parseArray(vo.getIds());
        log.info("idArr={}", idArr);
        for (int i = 0; i < idArr.size(); i++) {
            if (!ObjectId.isValid(idArr.getString(i))) {
                continue;
            }
            ObjectId oid = new ObjectId(idArr.getString(i));
            DevicePhotograph devicePhotograph = this.findById(oid);
            if (devicePhotograph != null) {
                this.delById(oid);
                try {
                    //删除oss文件
                    if (StringUtil.isNotBlank(devicePhotograph.getImage())) {
                        baseBucketTool.delFile(BaseBucketTool.PHOTOGRAPH_COMMON_PATH + devicePhotograph.getImage());
                    }
                    if (StringUtil.isNotBlank(devicePhotograph.getThumb())) {
                        baseBucketTool.delFile(BaseBucketTool.PHOTOGRAPH_COMMON_PATH + devicePhotograph.getThumb());
                    }
                } catch (Exception e) {
                    log.info("删除文件异常，不用处理");
                }
            }
        }
        return ResponseMap.success();
    }

    /**
     * @param imei
     * @time: 2021/3/13 10:36
     * @author: Rock
     * @version 1.0
     */
    public void delByImei(String imei) {
        Query query = new Query(Criteria.where("i").is(imei));
        //先查询
        List<DevicePhotograph> list = this.find(query);
        //再删除
        this.delByQuery(query);
        for (DevicePhotograph devicePhotograph : list) {
            if (devicePhotograph != null) {
                //删除oss文件
                try {
                    if (StringUtil.isNotBlank(devicePhotograph.getImage())) {
                        baseBucketTool.delFile(BaseBucketTool.PHOTOGRAPH_COMMON_PATH + devicePhotograph.getImage());
                    }
                    if (StringUtil.isNotBlank(devicePhotograph.getThumb())) {
                        baseBucketTool.delFile(BaseBucketTool.PHOTOGRAPH_COMMON_PATH + devicePhotograph.getThumb());
                    }
                } catch (Exception e) {
                    log.info("删除文件异常，不用处理");
                    continue;
                }
            }
        }
    }
}
